#!/bin/bash

# update classes
echo "Updating Classes..."
cd "${WORKDIR}"
[ ! -d "${DEST}" ] && mkdir -p "${DEST}"

# parse deps
echo "  |- parse deps"
mvn dependency:list -Dsort=true                                         \
    | grep -E '^\[INFO\]\s*\S+:\S+:\S+:\S+:\S+\s*$'                     \
    | sed -r 's/^\[INFO\]\s*(\S+):(\S+):(\S+):(\S+):(\S+)\s*$/\2-\4/g'  \
    > "${DEST}/dep.list.new"

# copy deps
echo "  |- copy deps"
mvn dependency:copy-dependencies -DoutputDirectory="${DEST}/deps" &> /dev/null
if [ "$?" -ne 0 ]; then
    echo "  |- copy deps failed,exited"
    exit 1
fi

# comparison new and old deps
[ ! -d "${DEST}/classes" ] && mkdir "${DEST}/classes"
cd "${DEST}/classes"

while read line
do
    if [ -f "${DEST}/deps/${line}.jar" ]; then
        flag="1"
        if [ -f "${DEST}/dep.class.list" ]; then
            for old_line in `cat "${DEST}/dep.class.list"`
            do
                if [ x"${old_line}" = x"${line}" ]; then
                    flag="2"
                    break
                fi
            done
        fi
        if [ x1 = x"${flag}" ]; then
            echo "  |- uncompress ${line}.jar to ${DEST}/classes"
            jar -xf "${DEST}/deps/${line}.jar"
        fi
    else
        echo "  |- ${line}.jar not exists"
    fi
done < "${DEST}/dep.list.new"

# replace old dep.class.list
echo "  |- move ${DEST}/dep.list.new to ${DEST}/dep.class.list"
mv -f "${DEST}/dep.list.new" "${DEST}/dep.class.list"

# uncompress jar
echo "  |- done!"
